<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <!-- 数据类型 -->
      <el-form-item label="数据类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择数据类型"
          @change="handleTypeChange"
        >
          <el-option label="均匀性" value="1" />
          <el-option label="热学" value="2" />
          <el-option label="热流" value="3" />
        </el-select>
      </el-form-item>

      <!-- 导入时间 -->
      <el-form-item label="导入时间" prop="importDay">
        <el-date-picker
          clearable
          v-model="queryParams.importDay"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择导入时间"
        />
      </el-form-item>

      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleDownloadTemplate">下载模板</el-button>
        <el-button type="success" icon="el-icon-upload" size="mini" @click="handleOpenImport">导入</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="数据类型" align="center" prop="type">
        <template slot-scope="scope">
          <span>
            {{ scope.row.type == 1 ? '均匀性' : scope.row.type == 2 ? '热学' : '热流' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="field1Label" align="center" prop="field1" />
      <el-table-column :label="field2Label" align="center" prop="field2" />
      <el-table-column label="导入时间" align="center" prop="importDay" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.importDay, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="180" />
      <el-table-column label="备注" align="center" prop="remark" />
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入弹窗 -->
    <el-dialog title="导入数据" :visible.sync="importOpen" width="500px" append-to-body>
      <el-form ref="importForm" :model="importForm" label-width="120px">
        <!-- 项目日期 -->
        <el-form-item label="项目日期" prop="importDay">
          <el-select
            v-model="importForm.importDay"
            placeholder="请选择项目日期"
            @change="handleExperimentDateChange"
          >
            <el-option
              v-for="item in experimentDates"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <!-- 时间范围 -->
        <el-form-item label="时间范围" prop="timeRange">
          <el-select v-model="importForm.timeRange" placeholder="请选择时间范围">
            <el-option
              v-for="item in experimentTimeRanges"
              :key="item.startTime + '-' + item.endTime"
              :label="item.startTime + '-' + item.endTime"
              :value="item.startTime + '-' + item.endTime"
            />
          </el-select>
        </el-form-item>

        <!-- 上传文件 -->
        <el-form-item label="选择文件" prop="file">
          <el-upload
            ref="upload"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleFileChange"
            :limit="1"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport">确 定</el-button>
        <el-button @click="importOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listData, getData, delData, addData, updateData } from "@/api/businessInfo/importData";
import request from "@/utils/request";

export default {
  name: "Data",
  data() {
    return {
      loading: true,
      total: 0,
      dataList: [],
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: "1",
        field1: null,
        field2: null,
        importDay: null,
      },
      // 导入相关
      importOpen: false,
      importForm: {
        importDay: null,
        timeRange: null,
        file: null,
      },
      fileList: [],
      experimentDates: [],
      experimentTimeRanges: [],
    };
  },
  computed: {
    field1Label() {
      if (this.queryParams.type == "1") return "量筒编号";
      if (this.queryParams.type == "2") return "钢板温度";
      if (this.queryParams.type == "3") return "时间";
      return "字段1";
    },
    field2Label() {
      if (this.queryParams.type == "1") return "液位高度";
      if (this.queryParams.type == "2") return "表面换热系数";
      if (this.queryParams.type == "3") return "钢板表面热流";
      return "字段2";
    },
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listData(this.queryParams).then((res) => {
        this.dataList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },

    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryParams.type = "1";
      this.handleQuery();
    },

    /** 类型切换 */
    handleTypeChange() {
      this.queryParams.field1 = null;
      this.queryParams.field2 = null;
      this.queryParams.pageNum = 1;
      this.handleQuery();
    },

    /** 下载模板 */
    handleDownloadTemplate() {
      const type = this.queryParams.type;
      const timeStamp = Date.now();
      let fileName;

      switch (type) {
        case "1":
          fileName = `均匀性数据导入模板_${timeStamp}.xlsx`;
          break;
        case "2":
          fileName = `热学数据导入模板_${timeStamp}.xlsx`;
          break;
        case "3":
          fileName = `热流数据导入模板_${timeStamp}.xlsx`;
          break;
        default:
          fileName = `数据导入模板_${timeStamp}.xlsx`;
      }

      // 发送 GET 请求获取模板 Blob
      request({
        url: "/business/importData/downloadTemplate",
        method: "get",
        params: { type },
        responseType: "blob"
      }).then((res) => {
        const blob = new Blob([res]);
        const url = window.URL.createObjectURL(blob);

        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", fileName); // 前端直接指定文件名
        document.body.appendChild(link);
        link.click();
        link.remove();
        window.URL.revokeObjectURL(url);
      });
    },

    /** 打开导入弹窗 */
    handleOpenImport() {
      this.importOpen = true;
      this.importForm = { importDay: null, timeRange: null, file: null };
      this.fileList = [];
      // 获取项目日期
      request({
        url: "/business/project/experimentTimes",
        method: "get",
      }).then((res) => {
        this.experimentDates = res.data;
      });
    },

    /** 项目日期选择变化 */
    handleExperimentDateChange(val) {
      this.importForm.timeRange = null;
      this.experimentTimeRanges = [];
      request({
        url: "/business/project/experimentTimeRangesByDate",
        method: "get",
        params: { experimentDate: val },
      }).then((res) => {
        this.experimentTimeRanges = res.data;
      });
    },

    /** 文件选择 */
    handleFileChange(file) {
      this.importForm.file = file.raw;
      this.fileList = [file];
    },

    /** 提交导入 */
    submitImport() {
      if (!this.importForm.importDay || !this.importForm.timeRange || !this.importForm.file) {
        this.$modal.msgError("请完整填写导入信息");
        return;
      }
      const [startTime, endTime] = this.importForm.timeRange.split("-");
      const formData = new FormData();
      formData.append("type", this.queryParams.type);
      formData.append("importDay", this.importForm.importDay);
      formData.append("startTime", startTime);
      formData.append("endTime", endTime);
      formData.append("file", this.importForm.file);

      request({
        url: "/business/importData/data",
        method: "post",
        data: formData,
        headers: { "Content-Type": "multipart/form-data" },
      }).then(() => {
        this.$modal.msgSuccess("导入成功");
        this.importOpen = false;
        this.getList();
      });
    },
  },
};
</script>
